<?php
namespace app\admin\controller;

use think\Controller;
use app\admin\model\Arctype as Arctypes;
use app\admin\model\ArctypeMod;

class Arctype extends Common
{
    private $cModel;   //当前控制器关联模型
    
    public function _initialize()
    {
        parent::_initialize();
        $this->cModel = new Arctypes;   //别名：避免与控制名冲突
    }
    
    public function index()
    {
        //$dataList = $this->cModel->treeList();
        $dataList = $this->cModel->where('pid',0)->order('id desc')->paginate('', false, page_param());
        foreach ($dataList as $k=>$v){
            // if ($v['arctypeMod']['mod'] == 'addonjump' && !empty($v['jumplink'])){
            //     $dataList[$k]['typelink'] = $v['jumplink'];
            // }else{
            //     $dataList[$k]['typelink'] = url('@category/'.$v['dirs']);
            // }
        }
        $this->assign('dataList', $dataList);
        return $this->fetch();
    }
    
    public function create()
    {
        if (request()->isPost()){
            $data = input('post.');
            if ($data['pid']==0 && !$data['number']) {
                return ajaxReturn('编号必须填写');
            }
            $result = $this->cModel->validate(CONTROLLER_NAME.'.add')->allowField(true)->save($data);
            cache('DB_TREE_ARETYPE', null);   //删除栏目缓存
            if ($result){
                return ajaxReturn(lang('action_success'), url('index'));
            }else{
                return ajaxReturn($this->cModel->getError());
            }
        }else{
            $arctypeList = $this->cModel->treeList();
            $this->assign('arctypeList', $arctypeList);
            
            $amModel = new ArctypeMod();
            $modList = $amModel->where(['status' => 1])->order('id ASC')->select();
            $this->assign('modList', $modList);
            return $this->fetch('edit');
        }
    }
    
    public function edit($id)
    {
        if (request()->isPost()){
            $data = input('post.');
            if ($data['pid']==0 && !$data['number']) {
                return ajaxReturn('编号必须填写');
            }
            if (count($data) == 2){
                foreach ($data as $k =>$v){
                    $fv = $k!='id' ? $k : '';
                }
                $result = $this->cModel->validate(CONTROLLER_NAME.'.'.$fv)->allowField(true)->save($data, $data['id']);
            }else{
                $result = $this->cModel->validate(CONTROLLER_NAME.'.edit')->allowField(true)->save($data, $data['id']);
            }
            cache('DB_TREE_ARETYPE', null);   //删除栏目缓存
            if ($result){
                return ajaxReturn(lang('action_success'), url('index'));
            }else{
                return ajaxReturn($this->cModel->getError());
            }
        }else{
            $arctypeList = $this->cModel->treeList();
            $this->assign('arctypeList', $arctypeList);
            
            $amModel = new ArctypeMod();
            $modList = $amModel->where(['status' => 1])->order('sorts ASC,id ASC')->select();
            $this->assign('modList', $modList);
            
            $data = $this->cModel->get($id);
            $this->assign('data', $data);
            return $this->fetch();
        }
    }
    
    public function delete()
    {
        if (request()->isPost()){
            $id = input('id');
            if (isset($id) && !empty($id)){
                $id_arr = explode(',', $id);
                $where = [ 'id' => ['in', $id_arr] ];
                $result = $this->cModel->where($where)->delete();
                cache('DB_TREE_ARETYPE', null);   //删除栏目缓存
                if ($result){
                    return ajaxReturn(lang('action_success'), url('index'));
                }else{
                    return ajaxReturn($this->cModel->getError());
                }
            }
        }
    }

    public function activecode(){
        $id = input('post.');
        $url = $_SERVER['HTTP_HOST'].'/arctype/'.$id['id'].'.html';
        ob_clean();
        vendor('phpqrcode.phpqrcode');

        if (strpos($url, 'http')===false) {
            $url='http://'.$url;
        }
        $filename = md5($id.time()).'.png';  //  生成的文件名  
        $errorCorrectionLevel = 'L';  // 纠错级别：L、M、Q、H  
        $matrixPointSize = 4; // 点的大小：1到10  
        \QRcode::png($url, $filename, $errorCorrectionLevel, $matrixPointSize, 2);   

        $image = \think\Image::open($filename);
        //生成目录
        $savePath = 'uploads'.DS.'hold';
        if ( !file_exists($savePath) ){
            mkdir($savePath);
        }
        $filePath = $savePath.DS.$filename;
        $rs = $image->save(ROOT_PATH.'public'.DS.$savePath.DS.$filename);
        if ($rs) {
            $this->cModel->update(['activecode'=>DS.$savePath.DS.$filename,'update_time'=>time()],$id);
            unlink($filename);
            return ajaxReturn(lang('action_success'), url('index'));
        }

    }


    public function downloadactive(){
        $dfile = tempnam('/tmp', 'tmp'); //产生一个临时文件，用于缓存下载文件
        vendor('download.zipfile');
        $zip = new \zipfile();
        //----------------------
        $filename = 'activecode.zip'; //下载的默认文件名
        $dataList = $this->cModel->select();

        $image = array();
        foreach ($dataList as $key => $val) {
            if ($val['activecode']) {
                 $image[$key]['image_src'] = ROOT_PATH . 'public'.$val['activecode'];
                 $image[$key]['image_name'] = $val['number'].'.jpg';
            }
        }

        foreach($image as $v){
          $zip->add_file(file_get_contents($v['image_src']), $v['image_name']);
          // 添加打包的图片，第一个参数是图片内容，第二个参数是压缩包里面的显示的名称, 可包含路径
          // 或是想打包整个目录 用 $zip->add_path($image_path);
        }
        //----------------------
        $zip->output($dfile);
         
        // 下载文件
        ob_clean();
        header('Pragma: public');
        header('Last-Modified:'.gmdate('D, d M Y H:i:s') . 'GMT');
        header('Cache-Control:no-store, no-cache, must-revalidate');
        header('Cache-Control:pre-check=0, post-check=0, max-age=0');
        header('Content-Transfer-Encoding:binary');
        header('Content-Encoding:none');
        header('Content-type:multipart/form-data');
        header('Content-Disposition:attachment; filename="'.$filename.'"'); //设置下载的默认文件名
        header('Content-length:'. filesize($dfile));
        $fp = fopen($dfile, 'r');
        while(connection_status() == 0 && $buf = @fread($fp, 8192)){
          echo $buf;
        }
        fclose($fp);
        @unlink($dfile);
        @flush();
        @ob_flush();
        exit();
    }
}